#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import requests
import json
import time

# API基础URL
BASE_URL = "http://localhost:8080"

def test_endpoint(method, url, data=None, headers=None):
    """测试API端点"""
    try:
        if headers is None:
            headers = {"Content-Type": "application/json"}
        
        if method.upper() == "GET":
            response = requests.get(url, headers=headers)
        elif method.upper() == "POST":
            response = requests.post(url, json=data, headers=headers)
        else:
            return False, f"不支持的HTTP方法: {method}"
        
        return True, response
    except Exception as e:
        return False, str(e)

def main():
    print("🔧 Android应用API端点测试")
    print("=" * 50)
    
    # 测试用户注册
    print("\n📝 测试用户注册...")
    username = f"androiduser{int(time.time())}"
    register_data = {
        "username": username,
        "password": "android123",
        "email": f"{username}@android.com"
    }
    
    success, response = test_endpoint("POST", f"{BASE_URL}/api/users/register", register_data)
    if success and response.status_code == 201:
        print("✅ 用户注册成功")
        user_data = response.json()
        print(f"   用户ID: {user_data.get('id')}")
        print(f"   用户名: {user_data.get('username')}")
        print(f"   角色: {user_data.get('role')}")
        user_id = user_data.get('id')
    else:
        print(f"❌ 用户注册失败: {response.status_code if success else 'Network Error'}")
        if success:
            print(f"   响应: {response.text}")
        return
    
    # 测试用户登录
    print("\n🔐 测试用户登录...")
    login_data = {
        "username": username,
        "password": "android123"
    }
    
    success, response = test_endpoint("POST", f"{BASE_URL}/api/users/login", login_data)
    if success and response.status_code == 200:
        print("✅ 用户登录成功")
        login_response = response.json()
        print(f"   用户ID: {login_response.get('id')}")
        print(f"   用户名: {login_response.get('username')}")
        print(f"   角色: {login_response.get('role')}")
        print(f"   Token: {login_response.get('token', 'N/A')}")
    else:
        print(f"❌ 用户登录失败: {response.status_code if success else 'Network Error'}")
        if success:
            print(f"   响应: {response.text}")
    
    # 测试获取用户信息
    print("\n👤 测试获取用户信息...")
    success, response = test_endpoint("GET", f"{BASE_URL}/api/user?userId={user_id}")
    if success and response.status_code == 200:
        print("✅ 获取用户信息成功")
        user_info = response.json()
        print(f"   用户名: {user_info.get('username')}")
        print(f"   邮箱: {user_info.get('email')}")
    else:
        print(f"❌ 获取用户信息失败: {response.status_code if success else 'Network Error'}")
        if success:
            print(f"   响应: {response.text}")
    
    # 测试用户登出
    print("\n🚪 测试用户登出...")
    success, response = test_endpoint("POST", f"{BASE_URL}/api/logout")
    if success and response.status_code == 200:
        print("✅ 用户登出成功")
        logout_response = response.json()
        print(f"   消息: {logout_response.get('message')}")
    else:
        print(f"❌ 用户登出失败: {response.status_code if success else 'Network Error'}")
        if success:
            print(f"   响应: {response.text}")
    
    # 测试重置密码
    print("\n🔑 测试重置密码...")
    reset_data = {"email": f"{username}@android.com"}
    success, response = test_endpoint("POST", f"{BASE_URL}/api/reset-password", reset_data)
    if success and response.status_code == 200:
        print("✅ 重置密码请求成功")
        reset_response = response.json()
        print(f"   消息: {reset_response.get('message')}")
    else:
        print(f"❌ 重置密码失败: {response.status_code if success else 'Network Error'}")
        if success:
            print(f"   响应: {response.text}")
    
    # 测试验证码
    print("\n🔢 测试验证码...")
    verify_data = {"email": f"{username}@android.com", "code": "123456"}
    success, response = test_endpoint("POST", f"{BASE_URL}/api/verify-code", verify_data)
    if success and response.status_code == 200:
        print("✅ 验证码验证成功")
        verify_response = response.json()
        print(f"   消息: {verify_response.get('message')}")
    else:
        print(f"❌ 验证码验证失败: {response.status_code if success else 'Network Error'}")
        if success:
            print(f"   响应: {response.text}")
    
    # 测试健康检查
    print("\n🏥 测试健康检查...")
    success, response = test_endpoint("GET", f"{BASE_URL}/api/health")
    if success and response.status_code == 200:
        print("✅ 健康检查成功")
        health_response = response.json()
        print(f"   状态: {health_response.get('status')}")
        print(f"   数据库: {health_response.get('database')}")
    else:
        print(f"❌ 健康检查失败: {response.status_code if success else 'Network Error'}")
        if success:
            print(f"   响应: {response.text}")
    
    print("\n" + "=" * 50)
    print("🎉 Android应用API端点测试完成!")

if __name__ == "__main__":
    main() 